package com.woniuxy.controller;

import com.woniuxy.bean.UserVo;
import com.woniuxy.pojo.Dept;
import com.woniuxy.pojo.User;
import com.woniuxy.service.DeptService;
import com.woniuxy.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController{
    private Logger logger= Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    /**
     * 控制器中的处理方法的返回值为跳转的路径
     * 本功能讲解从前台传递对象到控制器
     * 如果使用的是对象的传值，那些只要前台的表单的name的值和对象中的属性名的值相同就可以接收到数据
     */
    @RequestMapping(value = "/list")
    public String list(UserVo userVo,HttpServletRequest request){
        List<User> userList=userService.findUsersByPage(userVo);
        request.setAttribute("userlist",userList);
        request.setAttribute("uv",userVo);
        return "/user/list.jsp";
    }
    @RequestMapping(value = "/goAddUser")
    public ModelAndView goAddUser(){
        ModelAndView modelAndView=new ModelAndView();
        List<Dept> deptList=deptService.findAllDepts();
        //通过ModelAndView存放的数据全部是放在request域对象中的
        modelAndView.addObject("deptList",deptList);
        modelAndView.setViewName("/user/add.jsp");
        return modelAndView;
    }
    @RequestMapping(value = "/addUser")
    public String addUser(User user,
                          @RequestParam("file") MultipartFile file,
                          HttpServletRequest request){
        //获取服务器上路径
        String serverImageDirPath=request.getServletContext().getRealPath("/static/images");
        logger.debug("服务器上的图片文件夹的路径:"+serverImageDirPath);
        String imagePath=serverImageDirPath+"/"+file.getOriginalFilename();
        user.setHeadimg(file.getOriginalFilename());
        File uploadImage=new File(imagePath);
        try {
            file.transferTo(uploadImage);
            this.userService.addUser(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "list";
    }
}









